/*
 * @Author: 糊涂的老知青
 * @Date: 2022-08-13
 * @Version: 1.0.0
 * @Description:
 */
package eventbus

import (
	"fmt"
	"lzq-admin/config"
	"lzq-admin/pkg/eventbus/rabbitmq"
	"strings"
)

type EventBusOption struct {
	IsUse          bool   `mapstructure:"IsUse"`
	AppServiceName string `mapstructure:"AppServiceName"`
	MQUrl          string `mapstructure:"MQUrl"`
}

var EventBusOptions = &EventBusOption{}

func EventBusInit() {
	config.ViperConfig.Sub("eventbus").Unmarshal(EventBusOptions)
	connStrs := strings.Split(EventBusOptions.MQUrl, "|")
	connStrMap := make(map[string]string, 0)
	for _, v := range connStrs {
		vs := strings.Split(v, "=")
		connStrMap[strings.ToLower(vs[0])] = vs[1]
	}

	mqurl := fmt.Sprintf("amqp://%s:%s@%s/%s", connStrMap["username"], connStrMap["password"], connStrMap["host"], connStrMap["virtualhost"])
	queueNames := []string{"ActiveTest", "ActiveTest1", "ActiveTest2"}
	rabbitmq.NewRabbitMQWork(mqurl, queueNames)
}

type distributed struct {
}

var Distributed = distributed{}

func (d *distributed) PublishCommand(queueName, exchangeName, message, callbackName string) {
	rabbitmq.RabbitMQWorks[queueName].PublishWork(exchangeName, message, callbackName)
}

// 必须使用另外的进程进行监听队列
func (d *distributed) ComsumerCommand() {
	go func() {
		resu, err := rabbitmq.RabbitMQWorks["ActiveTest"].ConsumeWork()
		if err != nil {
			fmt.Println("消费错误", err.Error())
		}
		for d := range resu {
			fmt.Println(d.ConsumerTag+" test-qq消费成功:", string(d.Body))

			d.Ack(true) //需手动应答
		}
	}()
}
